package com.vend.common.task

import android.util.Log
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.annotations.NonNull
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.observers.DisposableObserver
import io.reactivex.rxjava3.schedulers.Schedulers


/**
 * Created by glendal on 2022/1/10.
 * 启用RxJava处理一步情况的逻辑
 */
object TaskExecutorVend {
    private val mCompositeDisposable = CompositeDisposable()
    fun call(task: ITask?) {
        //创建被观察者
        val observable = Observable.create<ITask> { emitter ->
            task?.onExecute()
            emitter!!.onComplete()
        }

        //创建观察者
        val disposableObserver: DisposableObserver<ITask?> = object : DisposableObserver<ITask?>() {
            override fun onNext(iTask: @NonNull ITask?) {
                Log.e("tag", "onNext: integer == ")
            }

            override fun onError(e: @NonNull Throwable?) {
                Log.e("tag", "onError: Error")
            }

            override fun onComplete() {
                Log.e("tag", "onComplete  Complete")
            }
        }

        //观察者订阅被观察者
        observable
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(disposableObserver)
       mCompositeDisposable.add(disposableObserver)
    }
    fun onDestory() {
        mCompositeDisposable.clear()
    }
}